import { UpdatePINFormDataProps } from '@/components/UpdatePIN/interface'
import { AppContext } from '@/pages/App/context'
import { useContext, useImperativeHandle, useRef, useState } from 'react'
import { PINViewProps } from '../interface'

const usePINHook = (props: PINViewProps, ref: any) => {
	const AppData = useContext(AppContext)
	const userInfo = AppData.user
	const pinRef = useRef<any>() //修改PIN码
	const oldData = {
		newPIN: '',
		currentPIN: '',
		confirmPIN: '',
	}
	const [newData, setNewData] = useState<any>({
		...oldData,
	})
	/**
	 * 暴露组件的方法
	 */
	useImperativeHandle(ref, () => ({
		/**保存数据 */
		saveData: () => {
			pinRef.current && pinRef.current.saveData()
		},
	}))
	const onChange = (formData: UpdatePINFormDataProps) => {
		setNewData({
			newPIN: formData.newPIN,
			currentPIN: formData.currentPIN,
			confirmPIN: formData.confirmPIN,
		})
		props.onChange && props.onChange(formData)
	}
	const toSave = () => {
		pinRef.current && pinRef.current.saveData()
	}
	return { pinRef, onChange, oldData, newData, toSave, userInfo }
}
export default usePINHook
